import React, { useEffect, useState } from 'react'
import {
  Button,
  DatePicker,
  Dropdown,
  Empty,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  notification,
  Radio,
} from 'antd'
import useGetTableData from '@/hooks/useGetTableData'
import {
  addBoxLabel,
  batchInvalidateBoxLabel,
  createByScanCode,
  deleteBoxLabel,
  queryBoxLabel,
  updatePreloadQty,
} from '@/api/purchase'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm, useWatch } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useBoxMarkColumns } from './columns'
import { PageDataBoxLabelVO, ITableData } from './types'
import CustomTable from '@/components/CustomTable'
import { OperationBoxmarkActionsType } from '@/constant'
import { useNavigate } from 'react-router-dom'
import { DownOutlined, ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons'
import { getSpuOptions } from '@/api/goods'
import { BOXMARK_STATUS_OPTIONS } from '@/constant/purchase'
import dayjs from 'dayjs'
import { onValuesChange } from '@/utils/onValuesChange'
import PermissionButton from '@/components/PermissionButton'
import useCachePage from '@/hooks/useCachePage'
import { useAppSelector } from '@/store/hooks'
import './BoxMark.less'
const Index: React.FC = () => {
  let SpuTimeout: ITimeoutType
  const navigate = useNavigate()
  const [form] = useForm()
  const [FormSend] = useForm()
  const [FormAdd] = useForm()
  const [isModalShow, setIsModalShow] = useState<boolean>(false)
  const boxLabelType = Form.useWatch('boxLabelType', FormAdd)
  const [isaddddModalShow, setIsaddModalShow] = useState<boolean>(false)
  const [SpuOptions, setSpuOptions] = useState<IOptionItem[]>([])
  const [SkuOptions, setSkuOptions] = useState<IOptionItem[]>([])
  const [selectKeys, setselectKeys] = useState<React.Key[]>([])
  const [selectInfos, setselectInfos] = useState<PageDataBoxLabelVO[]>([])
  const [tableData, settableData] = useState<ITableData[]>([])
  const [menuItems, setmenuItems] = useState<{ key: string; label: string }[]>([])
  const [currentInfo, setcurrentInfo] = useState<Record<string, any>>({})
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const { setCachePage, getCachePage } = useCachePage()
  const { tableProps, params, setParams, search, reset } = useGetTableData<ITableData>(queryBoxLabel, {
    form: form,
    defaultFieldsParams: {
      boxLabelStatues: [1, 3],
    },
    immediatelySend: false,
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
  })
  useEffect(() => {
    handleCacheData()
  }, [])
  useEffect(() => {
    settableData(tableProps.dataSource)
  }, [tableProps.dataSource])
  const handleCacheData = () => {
    const cacheData = getCachePage()
    if (cacheData == null) {
      search({ ...params, boxLabelStatues: [1, 3] })
      setCachePage({ ...params, boxLabelStatues: [1, 3] })
    } else {
      form.setFieldsValue({
        ...cacheData,
        boxLabelStatues: cacheData?.boxLabelStatues != null ? cacheData.boxLabelStatues : null,
      })
      setSpuOptions(cacheData?.SpuOptions || [])
      delete cacheData.SpuOptions
      search({
        ...cacheData,
        boxLabelStatues: cacheData?.boxLabelStatues != null ? cacheData.boxLabelStatues : null,
      })
    }
  }
  const selectRows = (keys: React.Key[], info: PageDataBoxLabelVO[]) => {
    setselectKeys(keys)
    setselectInfos(info)
  }
  const handleSearchSpuOptions = (newValue = '') => {
    if (!newValue) return
    if (SpuTimeout) {
      clearTimeout(SpuTimeout)
      SpuTimeout = null
    }
    const getOptions = async () => {
      const res = await getSpuOptions<{
        spuName: string
        spuCode: string
        designCode: string
      }>({ keyword: newValue })
      if (res.code === 200) {
        const data =
          res?.data?.map((item) => {
            return {
              label: `${item?.spuCode}｜${item.spuName}${item?.designCode ? '｜' + item?.designCode : ''}`,
              value: item.spuCode,
            }
          }) || []
        setSpuOptions(data)
      }
    }
    SpuTimeout = setTimeout(getOptions, 500)
  }
  const onModalCancel = () => {
    setIsModalShow(false)
    FormSend.resetFields()
    setIsaddModalShow(false)
    FormAdd.resetFields()
    setcurrentInfo({})
  }
  const onSendOk = async () => {
    const data = await FormSend.validateFields()
    console.log(selectInfos, 'selectInfos')
    const detailDTOList = selectInfos?.map((item) => {
      return {
        purchaseOrderCode: item.purchaseOrderCode,
        skuCode: item.skuCode,
        spuCode: item.spuCode,
        scheduleQty: item.scannedQty,
        boxLabelCode: item.boxLabelCode,
        orderQty: item.orderQty,
      }
    })
    const paramData = {
      scheduleDeliveryTime:
        data?.scheduleDeliveryTime && dayjs(data.scheduleDeliveryTime).format('YYYY-MM-DD HH:mm:ss'),
      detailDTOList: detailDTOList,
    }
    const res = await createByScanCode(paramData)
    if (res.code === 200) {
      setselectKeys([])
      setselectInfos([])
      onModalCancel()
      message.success('操作成功')
      search(params)
    }
    if (res.code === 820000 && res.failInfo) {
      const failInfo = JSON.parse(res.failInfo)?.map((item: string) => {
        return <div key={item}>箱唛条码：{item}</div>
      })
      notification.open({
        type: 'warning',
        message: res.msg,
        description: failInfo,
      })
    }
  }
  const onAddOk = async () => {
    const vals = await FormAdd.validateFields()
    const paramsData = Object.fromEntries(Object.entries(vals)?.filter(([_, val]) => val !== undefined))
    const res = await addBoxLabel({
      purchaseOrderCode: currentInfo?.purchaseOrderCode,
      skuCode: currentInfo?.skuCode,
      boxLabelCode: currentInfo?.boxLabelCode,
      reserveInvoiceCode: currentInfo?.reserveInvoiceCode,
      ...paramsData,
      addNum: paramsData.boxLabelType == 2 ? 1 : paramsData.addNum,
    })
    if (res?.code === 200) {
      setselectKeys([])
      setselectInfos([])
      message.success('操作成功')
      onModalCancel()
      search(params)
    }
  }
  const onSave = async (tableData: ITableData) => {
    const res = await updatePreloadQty({
      boxLabelCode: tableData.boxLabelCode,
      preloadQty: tableData.preloadQty,
    }).finally(() => reloadPgae())
    if (res.code === 200) {
      message.success('操作成功，修改数量后记得重新打印箱唛～')
    }
  }
  const reloadPgae = () => {
    search(params)
  }
  return (
    <PageContainer className="purchase_boxmark_page">
      <SearchForm
        params={params}
        form={form}
        onValuesChange={(changedValues) =>
          onValuesChange(changedValues, ['boxLabelCode', 'purchaseOrderCode', 'reserveInvoiceCode'], form)
        }
        searchConfig={[
          { label: '预约发货单号', name: 'reserveInvoiceCode', type: 'Input' },
          { label: '采购订单号', name: 'purchaseOrderCode', type: 'Input' },
          { label: '箱唛条码', name: 'boxLabelCode', type: 'Input' },
          {
            label: 'SPU商品',
            name: 'spuCode',
            type: 'Select',
            option: SpuOptions,
            placeholder: '款式编码/款式名称/助记码/工厂款号',
            config: {
              suffixIcon: null,
              showSearch: true,
              filterOption: false,
              optionFilterProp: 'label',
              onSearch: handleSearchSpuOptions,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          {
            label: 'SKU商品',
            name: 'skuCodeList',
            placeholder: '商品条码',
            type: 'Select',
            option: SkuOptions,
            config: {
              mode: 'tags',
              maxTagCount: 'responsive',
            },
          },
          {
            label: '箱唛状态',
            name: 'boxLabelStatues',
            type: 'Select',
            option: BOXMARK_STATUS_OPTIONS,
            config: {
              mode: 'multiple',
              maxTagCount: 'responsive',
              optionFilterProp: 'label',
            },
          },
          {
            label: '箱唛类型',
            name: 'boxLabelType',
            type: 'Select',
            option: [
              { label: '整箱', value: 1 },
              { label: '尾箱', value: 2 },
            ],
            config: {
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
            },
          },
          { label: '颜色', name: 'colorDetailName', type: 'Input', placeholder: '请输入颜色名称' },
          { label: '尺码', name: 'sizeInfo', type: 'Input', placeholder: '请输入尺码名称' },
        ]}
        onFinish={(vals: any) => {
          setselectKeys([])
          setselectInfos([])
          search({ ...vals, boxLabelStatues: vals?.boxLabelStatues?.length > 0 ? vals.boxLabelStatues : null })
          setCachePage({
            ...vals,
            boxLabelStatues: vals?.boxLabelStatues?.length > 0 ? vals.boxLabelStatues : null,
            SpuOptions,
            current: 1,
            size: params.size,
          })
        }}
        onReset={() => {
          setselectKeys([])
          setselectInfos([])
          setCachePage({ current: 1, size: 10, boxLabelStatues: [1, 3] })
          reset()
        }}
        initialValues={{ boxLabelStatues: [] }}
        extra={
          <div className="table_extra_flex">
            <PermissionButton
              permission="createBoxMark"
              type="primary"
              onClick={() => {
                navigate('/scan/boxmark/add')
              }}
              icon={<PlusOutlined />}
            >
              新建箱唛
            </PermissionButton>
            <PermissionButton
              permission="printBoxLabel"
              onClick={() => {
                if (selectKeys.length === 0) {
                  message.warning('请勾选需要操作的列表数据！')
                  return
                }
                const boxLabelCodes = selectInfos?.filter((item) => item.boxLabelStatus == 2)
                if (boxLabelCodes.length > 0) {
                  notification.warning({
                    message: '不符合打印条件，箱唛已作废',
                    description: boxLabelCodes?.map((item: any, index) => <div key={index}>{item.boxLabelCode}</div>),
                  })
                  return
                }
                const reserveInvoiceCodes = selectInfos?.filter(
                  (item) => item.boxLabelStatus != 2 && !item.reserveInvoiceCode,
                )
                if (reserveInvoiceCodes.length > 0) {
                  notification.warning({
                    message: '未预约发货，无法打印箱唛',
                    description: reserveInvoiceCodes?.map((item: any, index) => (
                      <div key={index}>{item.boxLabelCode}</div>
                    )),
                  })
                  return
                }
                navigate('/print?type=4', {
                  state: {
                    params: selectInfos.map((item) => item.boxLabelCode),
                  },
                })
              }}
            >
              打印箱唛
            </PermissionButton>
            <PermissionButton
              permission="printBoxMark"
              onClick={() => {
                if (selectKeys.length === 0) {
                  message.warning('请勾选需要操作的列表数据！')
                  return
                }
                navigate('/print?type=2', {
                  state: {
                    params: selectInfos,
                  },
                })
              }}
            >
              打印箱唛条码
            </PermissionButton>
            <PermissionButton
              permission="deliveryBoxMark"
              onClick={() => {
                if (selectKeys.length === 0) {
                  message.warning('请勾选需要操作的列表数据！')
                  return
                }
                const firstInfo = selectInfos[0]
                const isCommon = selectInfos.every((item) => item.purchaseOrderCode == firstInfo.purchaseOrderCode)
                if (!isCommon) {
                  message.warning('请勾选同一笔采购订单下的箱唛!')
                  return
                }
                setIsModalShow(true)
              }}
            >
              提交装箱
            </PermissionButton>
            <PermissionButton
              type="primary"
              permission="addBoxMark"
              onClick={() => {
                if (selectKeys.length === 0) {
                  message.warning('请勾选需要操作的列表数据！')
                  return
                }
                if (selectKeys.length > 1) {
                  message.warning('一次只能对一个预约发货单下的一个条码添加箱唛！')
                  return
                }
                const info = selectInfos[0]
                if (info?.reserveInvoiceStatus != 6) {
                  message.warning('预约发货单不处于扫码中状态！')
                  return
                }
                setIsaddModalShow(true)
                setcurrentInfo(info)
              }}
            >
              添加箱唛
            </PermissionButton>
            <PermissionButton
              type="primary"
              danger
              permission="delBoxMark"
              onClick={() => {
                if (selectKeys.length === 0) {
                  message.warning('请勾选需要操作的列表数据！')
                  return
                }
                const instance = Modal.confirm({
                  title: '提示',
                  content: '确认删除箱唛吗?',
                  okText: '确认',
                  cancelText: '取消',
                  icon: <ExclamationCircleOutlined />,
                  onOk: async () => {
                    const res = await deleteBoxLabel({
                      boxLabelCodes: selectInfos.map((item) => item.boxLabelCode),
                    }).finally(() => {
                      instance.destroy()
                      setselectKeys([])
                      setselectInfos([])
                      search(params)
                    })
                    if (res.code === 200) {
                      message.success('操作成功')
                    }
                    if (res.code === 820000 && res.failInfo) {
                      const failInfo = JSON.parse(res.failInfo)?.map((item: string) => {
                        return <div key={item}>{item}</div>
                      })
                      notification.open({
                        type: 'warning',
                        message: res?.msg,
                        description: failInfo,
                      })
                    }
                  },
                })
              }}
            >
              删除箱唛
            </PermissionButton>
            <PermissionButton
              permission="cancelBoxMark"
              onClick={() => {
                const instance = Modal.confirm({
                  title: '提示',
                  content: '箱唛作废后将无法扫描发货，确认操作吗?',
                  okText: '确认',
                  cancelText: '取消',
                  icon: <ExclamationCircleOutlined />,
                  onOk: async () => {
                    if (selectKeys.length === 0) {
                      message.warning('请勾选需要操作的列表数据！')
                      return
                    }
                    const res = await batchInvalidateBoxLabel({
                      boxLabelCodes: selectInfos.map((item) => item.boxLabelCode),
                    }).finally(() => {
                      instance.destroy()
                      setselectKeys([])
                      setselectInfos([])
                      search(params)
                    })
                    if (res.code === 200) {
                      message.success('操作成功')
                    }
                    if (res.code === 820000 && res.failInfo) {
                      const failInfo = JSON.parse(res.failInfo)?.map((item: string) => {
                        return <div key={item}>{item}</div>
                      })
                      notification.open({
                        type: 'warning',
                        message: '该箱唛状态无法作废',
                        description: failInfo,
                      })
                    }
                  },
                })
              }}
            >
              作废
            </PermissionButton>
          </div>
        }
      ></SearchForm>
      <CustomTable
        bordered
        columns={useBoxMarkColumns({ navigate, tableData, settableData, onSave, reloadPgae })}
        {...tableProps}
        rowKey={(rows) => rows.boxLabelId}
        isSelection
        selectRows={selectRows}
        selectedRowKeys={selectKeys}
        tableRowGray={(record) => (record.boxLabelStatus && record.boxLabelStatus == 2 ? 'table-row-gray' : '')}
        isScrollY
        pageSizeOptions={[10, 30, 100, 500]}
        preserveSelectedRowKeys={false}
      />
      <Modal title="提交装箱" open={isModalShow} onCancel={onModalCancel} onOk={onSendOk}>
        <Form form={FormSend} layout="vertical" initialValues={{ scheduleDeliveryTime: dayjs() }}>
          <Form.Item
            label="预约发货时间"
            name="scheduleDeliveryTime"
            style={{ marginBottom: 0 }}
            rules={[
              {
                required: true,
                message: '请选择预约发货时间',
              },
            ]}
          >
            <DatePicker showTime></DatePicker>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        className="box_mark_modal_wrap"
        title="添加箱唛"
        open={isaddddModalShow}
        onCancel={onModalCancel}
        onOk={onAddOk}
      >
        <Form form={FormAdd} layout="vertical" initialValues={{ boxLabelType: 1 }}>
          <div className="box_mark_modal_add_infos">
            <div className="bmma_column">
              <span>预约发货单号：</span>
              <span className="bc_text_color">{currentInfo?.reserveInvoiceCode || '-'}</span>
            </div>
            <div className="bmma_column">
              <span>商品条码：</span>
              <span className="bc_text_color">{currentInfo?.skuCode || '-'}</span>
            </div>
          </div>
          <Form.Item
            label="需要添加的箱唛类型"
            name="boxLabelType"
            rules={[
              {
                required: true,
                message: '请选择需要添加的箱唛类型',
              },
            ]}
          >
            <Radio.Group
              options={[
                { label: '整箱', value: 1 },
                { label: '尾箱', value: 2 },
              ]}
            ></Radio.Group>
          </Form.Item>
          {boxLabelType == 1 && (
            <Form.Item
              label="需要添加几个箱唛"
              name="addNum"
              rules={[
                {
                  required: boxLabelType == 1,
                  message: '请输入箱唛数量',
                },
              ]}
            >
              <InputNumber min={1} placeholder="请输入箱唛数量" style={{ maxWidth: 250 }} precision={0}></InputNumber>
            </Form.Item>
          )}
          {boxLabelType == 2 && (
            <Form.Item
              label="尾箱还剩几件"
              name="preLoadNum"
              rules={[
                {
                  required: boxLabelType == 2,
                  message: '请输入还剩几件',
                },
              ]}
            >
              <InputNumber min={1} placeholder="请输入还剩几件" style={{ maxWidth: 250 }} precision={0}></InputNumber>
            </Form.Item>
          )}
        </Form>
      </Modal>
    </PageContainer>
  )
}

export default Index
